package com.loyin.ds;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DBConnectionManager
{
	private Connection	dbConnection;
	private List<PreparedStatement> preparedStatementList = new ArrayList();
	
	public DBConnectionManager(String dataSourceName)
	{
		dbConnection = null;
		try
		{
			Context ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup("java:comp/env/"+dataSourceName);//tomcat写法
//			DataSource ds = (DataSource) ctx.lookup("java:"+dataSourceName);		//jboss写法
//			DataSource ds = (DataSource) ctx.lookup(dataSourceName); //weblogic写法
			if (ds != null)
			{
				dbConnection = ds.getConnection();
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public Connection getDbConnection()
	{
		return dbConnection;
	}
		
	public PreparedStatement getPrepstmt(String sql)
	{
		PreparedStatement prepstmt=null;
		try
		{
			prepstmt = dbConnection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
			preparedStatementList.add(prepstmt);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return prepstmt;
		
	}
	
	public void closeDbconnection()
	{
		//关闭所有的查询
		if(preparedStatementList!=null && preparedStatementList.size()>0)
		{
			for(PreparedStatement prepstmt:preparedStatementList)
			{
				try
				{
					if (prepstmt != null)
					{
						prepstmt.close();
						prepstmt = null;
					}
				} 
				catch (SQLException se)
				{
					se.printStackTrace();
				}
			}
		}
		//关闭数据库连接
		try
		{
			if (dbConnection != null && !dbConnection.isClosed())
			{
				dbConnection.close();
				dbConnection = null;
			}
		} catch (SQLException se)
		{
			se.printStackTrace();
		}
	}
	
	
	
	
	
}
